<template>

	<view class="content">
		<view>
			<u-navbar :is-back="false" :placeholder="true" title="微聊" :bgColor="'#e9e9ea'" :leftIcon="''" :border="true"
				z-index="10076">
				<view slot="center" style="color: #000;font-size: 30rpx;">
					聊天面板
				</view>
				<view class="slot-wrap" slot="right">
					<u-icon name="search" size="24" color="#000" style="margin-right: 15rpx;"
						@click="$u.route({url:'/pages/serch/serch'})"></u-icon>
					<u-icon name="plus-circle" size="20" color="#000" @click="selectShow = !selectShow"></u-icon>
				</view>
			</u-navbar>
		</view>

		<selectInput :list="selectList" :list-key="'name'" v-if="selectShow" :show.sync="selectShow"
			@on-select="checkSelect" @close="closeSelect" />
		<u-list style="height: auto;">
			<u-list-item v-for="(val, key) in $historylst" :key="key">
				<u-cell>
					<view @longtap="showtip=true" slot="title"
						style="justify-content:space-between;width: 350rpx;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;">
						<text>{{val.name}}</text>
						<text
							style="font-size: 26rpx;color: #ccc;margin-top: 10rpx;display: block;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;">
							{{val.list[val.list.length - 1].Content}}
						</text>
					</view>
					<view @longtap="showtip=true" slot="right-icon"
						style="display: flex;flex-direction: column;justify-content:space-between;width: 200rpx;text-align: right;">
						<text
							style="font-size: 24rpx;">{{$u.timeFormat(new Date(val.list[val.list.length - 1].Time).getTime(), 'mm月dd日 hh:MM')}}</text>
						<text style="display: block;margin-top: 10rpx;">
							<u-badge style="text-align: right;float: right;" :type="'info'" max="99"
								:value="val.length"></u-badge>
						</text>
					</view>

					<u-avatar @longtap="showtip=true" slot="icon" shape="square" size="45" :src="val.Top"
						customStyle="margin: -3px 5px -3px 0"></u-avatar>
				</u-cell>
			</u-list-item>
		</u-list>
		<u-popup :show="showtip" mode="center" :customStyle="{width:'60%'}" :closeOnClickOverlay="false"
			@close="close()" :round="7" :closeable="true">
			<view style="padding: 10px;padding-top: 35px;">
				<u-button size="mini" type="success"
					style="margin: 10px 0;padding: 0 90px;height:35px;line-height: 35px; display: block;font-size: 26rpx;">
					置顶</u-button>
				<u-button size="mini" type="error"
					style="margin: 10px 0;padding: 0 90px;height: 35px;line-height: 35px;display: block;font-size: 26rpx;margin-top: 10rpx;">
					删除</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import selectInput from '@/components/selectInput/selectInput.vue';
	export default {
		components: {
			selectInput
		},
		data() {
			return {
				urls: [
					'https://cdn.uviewui.com/uview/album/1.jpg',
					'https://cdn.uviewui.com/uview/album/2.jpg',
					'https://cdn.uviewui.com/uview/album/3.jpg',
				],
				showtip: false,
				nowtap: {},
				selectShow: false,
				selectList: [{
					id: '1',
					name: '添加朋友',
					icon: 'man-add-fill'
				}, {
					id: '2',
					name: '扫一扫',
					icon: 'scan'
				}, {
					id: '3',
					name: '收付款',
					icon: 'fingerprint'
				}]
			};
		},
		onShow() {
			console.log(this.$historylst)
		},
		computed: {},
		onLoad() {
			var _this = this;
			if (!this.$token) {
				return;
			}
			uni.$on("initSocket", () => { //初始化sock
				this.initSocket();
			})
			uni.$on("initdata", () => { //初始化数据
				this.initdata();
			})
			uni.$on("sendSocketMessage", (e) => {
				// console.log(e)
				this.sendSocketMessage(e)
			})
			this.initSocket();
			this.initdata();
			// this.getlist();
			// this.getbiao();//设置未读信息角标 聊天
			// this.getbiao1();//设置未读信息角标 验证
			// this.getbiao2();//设置未读信息角标 朋友圈
		},
		methods: {
			async initdata() {
				var res = await uni.$u.http.get('/getFried', {
					params: {
						pid: this.$userInfo.ID
					}
				}, {})
				if (res.state == 200) {
					this.$store.state.$friend = res.data;
					uni.savedata("friend", res.data, '7d')
				}
			},
			initSocket() {
				var _this = this;
				uni.connectSocket({
					url: _this.wsurl + "/" + _this.$userInfo.ID + "/" + _this.$token,
					data() {
						return {
							id: _this.$userInfo.ID
						};
					},
					header: {
						'content-type': 'application/json',
					},
					method: 'GET'
				});
				uni.onSocketOpen((res) => {
					this.$store.state.socketOpen = true;
					console.log('WebSocket连接已打开！');
					// setInterval(()=>{
					// var data = {
					// 	"Cid": 0,
					// 	"Fid": 2,
					// 	"Type": "",
					// 	"Topimg": "",
					// 	"Content": "",
					// 	"Other": "",
					// 	"Username": "",
					// 	"Phone": null,
					// 	"Name": "",
					// 	"Datatype": 'addcontact',
					// 	"Msg": ''
					// }
					// this.sendSocketMessage(data)
					// },5000)

				});
				this.onmsg();
				uni.onSocketError((res) => {
					return
					this.$store.state.socketOpen = false;
					console.log(res, 'WebSocket连接打开失败，3秒后尝试重新链接！');
					setTimeout(() => {
						uni.connectSocket({
							url: _this.wsurl + "/" + _this.$userInfo.ID + "/" + _this.$token,
							data() {
								return {
									uid: _this._user_info.userId
								};
							},
							header: {
								'content-type': 'application/json',
								'Authorization': _this.$token
							},
							method: 'GET'
						});
					}, 3000)
				});
			},
			sendSocketMessage(msg) {
				if (this.socketOpen) {
					// console.log(123)
					//推送格式{"Cid":0,"Fid":0,"Type":"","Topimg":"","Content":"","Time":"","Other":"",Username:"",Phone:null,Name:"",Datatype:'',Msg:'',State:''}
					uni.sendSocketMessage({
						data: JSON.stringify(msg),
						success(e) {
							console.log(e)
						},
						fail(e) {
							console.log(e)
						}
					});
				}
			},
			onmsg() {
				uni.onSocketMessage(function(res) {
				 console.log('收到服务器内容：' + res.data);
					var datatype = JSON.parse(res.data); 
					var arr = Array.isArray(datatype)?datatype:[datatype];
					console.log(arr)
					for(let asd in arr){
						let msg = arr[asd];
						if (msg.Datatype == "addcontact") {
							return
						}
						if (msg.Datatype == "setcontact") {
							return
						}
						let list = uni.getdata("historylst");
						if (!list) {
							list = {}
							list[msg.Cid + 'key'] = {
								name: msg.Name ? msg.Name : msg.Username,
								Cid: msg.Cid,
								list: [msg],
								Top: msg.Top,
								lenght:1
							}
							uni.savedata("historylst", list);
							this.$store.state.$historylst = list;
							return
						}
						if (!list[msg.Cid + 'key']) {
							list[msg.Cid + 'key'] = {
								name: msg.Name ? msg.Name : msg.Username,
								Cid: msg.Cid,
								list: [msg],
								Top: msg.Top,
								lenght:1
							}
						} else {
							
								let Cid = msg.Fid;
								let Fid = msg.Cid;
								msg.Fid = Fid;
								msg.Cid = Cid;
								if(!list[msg.Cid + 'key'].list){
									list[msg.Cid + 'key'].list = [];
								}
								list[msg.Cid + 'key'].list.push(msg);
								list[msg.Cid + 'key'].length = list[msg.Cid + 'key'].length +1;
							
						}
						uni.savedata("historylst", list);
						this.$store.state.$historylst = list;
					}
					//数据格式 {"Msg":"token错误！","State":400,Datatype:"m","Cid":0,"Fid":0,"Type":"","Topimg":"","Content":"","Time":"","Other":"",Username:"",Phone:null,Name:""}
				});
			},
			open() {},
			close() {
				this.showtip = false
			},

			//打开或者关闭弹窗
			showSelect() {
				this.selectShow = !this.selectShow;
			},
			//action 点击事件
			click(index, index1) {

			},

			//点击导航栏自定义按钮
			onNavigationBarButtonTap({
				index
			}) {
				if (index == 0) {
					this.showSelect()
				}
			},
			//跳转
			linkTo({
				id,
				name,
				images,
				userId
			}) {
				this.$u.route({
					url: 'pages/chat/chat',
					params: {
						messageId: id,
						fromUserId: userId
					}
				});
			},
			//关闭弹窗
			closeSelect() {
				//小程序兼容
				this.selectShow = false;
			},
			//扫码
			checkSelect(index) {
				// console.log(index)
				if (index == 0) {
					this.$u.route({
						url: 'pages/add/add'
					})
				} else if (index == 1) {
					// uni.vibrateLong();

					//扫码
					uni.scanCode({
						success: function(res) {
							// console.log('条码内容：' + res.result);
							this.$u.toast('条码类型:', res.scanType);
						}
					});
				}
			},
			getbiao() {

			},
			getbiao1() {

			},
			getbiao2() {

			}
		},
		watch: {

		}

	};
</script>
<style>

</style>
<style lang="scss" scoped>
	.content {
		.message-hover-class {
			opacity: .5;
		}

		.slot-wrap {
			display: flex;
			align-items: center;
			padding: 0 0rpx;
		}
	}
</style>
